package com.joker.airoleplayplatformback.config;

import com.joker.airoleplayplatformback.service.UserService;
import com.joker.airoleplayplatformback.utils.JwtUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Spring Security配置
 *
 * @author feixiang.li
 * @since 2025-09-27
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


//    @Bean
//    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
//        http
//                .csrf().disable()  // 如果使用 JWT，通常会禁用 CSRF
//                .authorizeRequests()
//                .antMatchers("/login", "/register").permitAll() // 登录、注册无需认证
//                .anyRequest().authenticated()  // 其他请求需要认证
//                .and()
//                .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // 在 Spring Security 的默认认证过滤器之前加入 JWT 认证过滤器
//
//        return http.build();
//    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, UserService userService, JwtUtils jwtUtils) throws Exception {
        http
                // 禁用CSRF
                .csrf(csrf -> csrf.disable())
                // 配置CORS
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 配置会话管理
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置权限
                .authorizeHttpRequests(authz -> authz
                        // 允许所有用户访问的接口
                        .requestMatchers(
                                "/api/auth/**",           // 认证接口
                                "/api/knowledge/**",      // 知识库接口（按需求开放）
                                "/api/agents/**",         // 智能体接口
                                "/ws/**",                 // WebSocket接口
                                "/swagger-ui/**",         // Swagger文档
                                "/swagger-ui.html",
                                "/swagger-resources/**",
                                "/v1/api-docs/**",        // API文档
                                "/api/1.0/oss/**",
                                "/doc.html"               // Knife4j文档
                        ).permitAll()
                        // 其他接口需要认证
                        .anyRequest().authenticated()

                ).addFilterBefore(new JWTAuthenticationFilter(userService, jwtUtils), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
